package jsyf.oa.service.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.oa.dao.system.*;
import jsyf.oa.entity.system.TargetEntity;
import jsyf.oa.entity.system.TargetRoleEntity;
import jsyf.oa.facade.system.TargetRoleFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.stream.events.EndDocument;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by WHH-PC on 2018/1/26.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class TargetRoleService implements TargetRoleFacade {

    @Autowired
    private TargetRoleDao targetRoleDao;
    @Autowired
    private TargetDao targetDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RegionDao regionDao;
    @Autowired
    private LeaveDao leaveDao;

    @Override
    public String save(String jsonData) {
        TargetRoleEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), TargetRoleEntity.class);
        //删除某个公司区域经理目标
        targetRoleDao.removeByCondition(" AND COMPANY_ID = ? AND TARGET_TYPE=0 ", new String[]{entity.getCompanyId()});
        String roleIds = "'" + entity.getSalerRoleId() + "'";
        //区域经理目标
        TargetRoleEntity salerEntity = new TargetRoleEntity();
        salerEntity.setCompanyId(entity.getCompanyId());
        salerEntity.setRoleNameId(entity.getSalerRoleId());
        salerEntity.setFaceTarget(entity.getSalerFaceTarget());
        salerEntity.setTelTarget(entity.getSalerTelTarget());
        salerEntity.setCreateUserId(entity.getCreateUserId());
        salerEntity.setTargetType(0);
        targetRoleDao.add(salerEntity);


        Calendar calendar = Calendar.getInstance();//获取当前日期

        //获取前月的第一天
        String firstDay = DateUtils.getFirstDayOfMonth();
        //获取当月天数
        Integer days = DateUtils.getLastDayOfMonth(calendar.get(calendar.YEAR), calendar.get(calendar.MONTH) + 1);
        String month = DateUtils.parse(calendar.getTime(), "yyyy-MM");
        //查询某个公司区域经理人员
        List<JSONObject> userList = userDao.getViewJSONListByCondition("  AND main = 1 AND companyId = ?" +
                        "AND (jobState <> 1 " +
                        "OR (jobState = 1 && LEFT(leaveDate,7) = " + "'" + month + "'))" +
                        " AND roleId IN(SELECT ID FROM T_SYS_ROLE WHERE ROLE_NAME_ID " +
                        "IN (SELECT ID FROM T_SYS_ROLE_NAME WHERE ID IN (" + roleIds + "))) ",
                new Object[]{entity.getCompanyId()});

        //清除当月目标
        Date day = targetRoleDao.getCurrentTime();
        String nowMonth = DateUtils.parse(day, "yyyy-MM");
        targetDao.removeByCondition(" AND LEFT(TARGET_DATE,7) >= ? AND COMPANY_ID = ?  AND TARGET_TYPE=0", new String[]{nowMonth, entity.getCompanyId()});

        //生成一段时间的目标（这里生成一个月的目标）
        List<TargetEntity> targetEntityList = new ArrayList<>();
        for (Integer i = 0; i < userList.size(); i++) {
            String userId = userList.get(i).get("id").toString();
            for (Integer j = 1; j <= days; j++) {
                TargetEntity targetEntity = new TargetEntity();
                String targetDate = firstDay.substring(0, 7) + "-" + (j < 10 ? "0" + j : j);
                if (
                        !userList.get(i).getString("jobState").equals("1")
                                ||
                                (
                                        userList.get(i).getString("jobState").equals("1")
                                                && (userList.get(i).getString("leaveDate").compareTo(targetDate) > 0)
                                )
                        ) {
                    targetEntity.setUserId(userId);
                    targetEntity.setTargetDate(targetDate);
                    targetEntity.setCompanyId(entity.getCompanyId());
                    targetEntity.setCreateUserId(entity.getCreateUserId());
                    //查询销售的所在区域id
                    JSONObject regionJson = regionDao.getRegionByRoleName(userId, " AND PARENT_ID != '0'");
                    if (regionJson != null) {
                        targetEntity.setRegionId(regionJson.get("id").toString());
                    }
                    //查询销售的大区id
                    JSONObject bigRegionJson = regionDao.getRegionByRoleName(userId, " AND PARENT_ID = '0'");
                    if (regionJson != null) {
                        targetEntity.setBigRegionId(bigRegionJson.get("id").toString());
                    }
                    List<JSONObject> leaveLists = leaveDao.getJSONListByCondition(" AND USER_ID=? AND LEFT(BEGIN_TIME,7)=?", new Object[]{userId, nowMonth});
                    if (leaveLists != null && leaveLists.size() > 0) {
                        for (int k = 0; k < leaveLists.size(); k++) {
                            if (leaveLists.get(k).getString("leaveDate").equals(targetDate)) {
                                targetEntity.setFaceTarget(0);
                                targetEntity.setTelTarget(0);
                            } else {
                                targetEntity.setFaceTarget(entity.getSalerFaceTarget());
                                targetEntity.setTelTarget(entity.getSalerTelTarget());
                            }
                        }
                    } else {
                        targetEntity.setFaceTarget(entity.getSalerFaceTarget());
                        targetEntity.setTelTarget(entity.getSalerTelTarget());
                    }
                    targetEntityList.add(targetEntity);
                }
            }
        }
        targetDao.insertBatch(targetEntityList);
        return entity.getId();
    }

    @Override
    public String saveBigCustomer(String jsonData) {
        TargetRoleEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), TargetRoleEntity.class);
        //删除某个公司大客户经理目标
        targetRoleDao.removeByCondition(" AND COMPANY_ID = ? AND TARGET_TYPE=1", new String[]{entity.getCompanyId()});
        String roleIds = "'" + entity.getSalerRoleId() + "'";
        //大客户经理目标
        TargetRoleEntity salerEntity = new TargetRoleEntity();
        salerEntity.setCompanyId(entity.getCompanyId());
        salerEntity.setRoleNameId(entity.getSalerRoleId());
        salerEntity.setFaceTarget(entity.getSalerFaceTarget());
        salerEntity.setTelTarget(entity.getSalerTelTarget());
        salerEntity.setTargetType(1);
        salerEntity.setCreateUserId(entity.getCreateUserId());
        targetRoleDao.add(salerEntity);


        Calendar calendar = Calendar.getInstance();//获取当前日期

        //获取前月的第一天
        String firstDay = DateUtils.getFirstDayOfMonth();
        //获取当月天数
        Integer days = DateUtils.getLastDayOfMonth(calendar.get(calendar.YEAR), calendar.get(calendar.MONTH) + 1);
        String month = DateUtils.parse(calendar.getTime(), "yyyy-MM");
        //查询某个公司大客户经理经理人员
        List<JSONObject> userList = userDao.getViewJSONListByCondition("  AND main = 1 AND companyId = ?" +
                        "AND (jobState <> 1 " +
                        "OR (jobState = 1 && LEFT(leaveDate,7) = " + "'" + month + "'))" +
                        " AND roleId IN(SELECT ID FROM T_SYS_ROLE WHERE ROLE_NAME_ID " +
                        "IN (SELECT ID FROM T_SYS_ROLE_NAME WHERE ID IN (" + roleIds + "))) ",
                new Object[]{entity.getCompanyId()});

        //清除当月目标
        Date day = targetRoleDao.getCurrentTime();
        String nowMonth = DateUtils.parse(day, "yyyy-MM");
        targetDao.removeByCondition(" AND LEFT(TARGET_DATE,7) >= ? AND COMPANY_ID = ? AND TARGET_TYPE=1", new String[]{nowMonth, entity.getCompanyId()});

        //生成一段时间的目标（这里生成一个月的目标）
        List<TargetEntity> targetEntityList = new ArrayList<>();
        for (Integer i = 0; i < userList.size(); i++) {
            String userId = userList.get(i).get("id").toString();
            for (Integer j = 1; j <= days; j++) {
                TargetEntity targetEntity = new TargetEntity();
                String targetDate = firstDay.substring(0, 7) + "-" + (j < 10 ? "0" + j : j);
                if (
                        !userList.get(i).getString("jobState").equals("1")
                                ||
                                (
                                        userList.get(i).getString("jobState").equals("1")
                                                && (userList.get(i).getString("leaveDate").compareTo(targetDate) > 0)
                                )
                        ) {
                    targetEntity.setUserId(userId);
                    targetEntity.setTargetDate(targetDate);
                    targetEntity.setCompanyId(entity.getCompanyId());
                    targetEntity.setCreateUserId(entity.getCreateUserId());
                    List<JSONObject> leaveLists = leaveDao.getJSONListByCondition(" AND USER_ID=? AND LEFT(BEGIN_TIME,7)=?", new Object[]{userId, nowMonth});
                    if (leaveLists != null && leaveLists.size() > 0) {
                        for (int k = 0; k < leaveLists.size(); k++) {
                            if (leaveLists.get(k).getString("leaveDate").equals(targetDate)) {
                                targetEntity.setFaceTarget(0);
                                targetEntity.setTelTarget(0);
                            } else {
                                targetEntity.setFaceTarget(entity.getSalerFaceTarget());
                                targetEntity.setTelTarget(entity.getSalerTelTarget());
                            }
                        }
                    } else {
                        targetEntity.setFaceTarget(entity.getSalerFaceTarget());
                        targetEntity.setTelTarget(entity.getSalerTelTarget());
                    }
                    targetEntityList.add(targetEntity);
                }
            }
        }
        targetDao.insertBatch(targetEntityList);
        return entity.getId();
    }

    @Override
    public List<JSONObject> getTargetRole(String companyId) {
        return targetRoleDao.getJSONListByCondition(" AND COMPANY_ID = ?", new Object[]{companyId});
    }
}
